<template>
  <div class="page-top10-container">
    <!-- 标题和日期选择器 -->
    <div class="header-section">
      <div class="title-section">
        <h3 class="widget-title">页面访问Top10</h3>
        <div class="date-selector">
          <div class="date-nav">
            <i class="el-icon-arrow-left date-arrow" :class="{ 'disabled': !canGoPrev }" @click="prevDate"></i>
            <span class="date-text">{{ currentDate }}</span>
            <i class="el-icon-arrow-right date-arrow" :class="{ 'disabled': !canGoNext }" @click="nextDate"></i>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选按钮组 -->
    <div class="filter-buttons">
      <el-button 
        v-for="(filter, index) in filterOptions" 
        :key="filter.name"
        :type="activeFilter === index ? 'primary' : ''"
        :class="{ 'active': activeFilter === index }"
        @click="changeFilter(index)"
        class="filter-btn"
        v-show="!filter.disabled"
      >
        {{ filter.name }}
      </el-button>
    </div>

    <!-- 条形图数据展示 -->
    <div class="chart-container">
      <!-- 有数据时显示图表 -->
      <div v-if="chartData && chartData.length > 0">
        <div class="chart-item" v-for="(item, index) in chartData" :key="index">
          <div class="item-label">{{ item.name }}</div>
          <div class="bar-value-left">{{ item.count }}</div>
          <div class="bar-container">
            <div class="bar-fill" :style="{ width: item.percentage + '%' }"></div>
          </div>
          <div class="bar-value-right">{{ item.percentage }}%</div>
        </div>
      </div>
      <!-- 无数据时显示提示 -->
      <div v-else class="no-data-container">
        <div class="no-data-icon">
          <i class="el-icon-data-line"></i>
        </div>
        <div class="no-data-text">暂无数据</div>
        <div class="no-data-desc">当前日期没有访问数据</div>
      </div>
    </div>
  </div>
</template>

<script>
import { getVisitFunctionTopData } from '@/api/chenlong.js'
export default {
  name: 'PageTop10',  //页面访问TOP10
  props:{
    corpId: {
      type: String,
      default: ''
    },
    dateRange: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      activeFilter: 0, // 默认选中"访问人数"
      currentDate: '',
      currentPickDate: new Date(), // 当前选择的日期，默认为今天
      filterOptions: [
        // { name: '指标筛选', disabled: false },
        { name: '访问人数', disabled: false },
        { name: '打开次数', disabled: false },
        { name: '访问页面数', disabled: true }
      ],
      chartData: []
    }
  },
  mounted() {
    // 初始化当前日期显示
    if (this.dateRange && this.dateRange.length > 0) {
      const lastDay = new Date(this.dateRange[1])
      this.currentPickDate = lastDay
      this.currentDate = this.formatTimeDisplay(this.formatDateForApi(this.currentPickDate))
    } else {
      this.currentDate = this.formatTimeDisplay(this.formatDateForApi(this.currentPickDate))
    }
    this.gentCurrentData()
  },
  watch: {
    corpId: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.gentCurrentData()  // corpId变化时更新数据
        }
      }
    },
    dateRange: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          // 当dateRange变化时，更新当前日期显示为dateRange的最后一天
          if (newVal && newVal.length > 0) {
            const lastDay = new Date(newVal[1])
            this.currentPickDate = lastDay
            this.currentDate = this.formatTimeDisplay(this.formatDateForApi(this.currentPickDate))
          }
          this.gentCurrentData()
        }
      }
    }
  },
  computed: {
    // 日期切换判断逻辑
    canGoPrev() {
      // 判断是否可以点击左箭头（前一天）- 可以点击过去时间
      if (!this.currentPickDate) return false
      // 左箭头总是可以点击，因为可以查看过去的数据
      return true
    },

    canGoNext() {
      // 判断是否可以点击右箭头（后一天）- 不能点击未来时间
      if (!this.currentPickDate) return false
      const today = new Date()
      today.setHours(23, 59, 59, 999)
      const nextDate = new Date(this.currentPickDate)
      nextDate.setDate(nextDate.getDate() + 1)
      return nextDate <= today
    }
  },
  methods: {
    async gentCurrentData() {
      const params = {
        corpId: this.corpId || '',
        time: this.getLastDay(),
        type: this.filterOptions[this.activeFilter].name
      }
      // console.log(params)
      const res = await getVisitFunctionTopData(params)
      if (res.code == 200) {
        this.chartData = res.data.map(item => {
          return {
            name: item.module_name,
            count: item.count,
            percentage: item.percentage
          }
        })
      }
    },

    async updateDataByDate() {
      // 根据选择的日期更新数据
      const params = {
        corpId: this.corpId || '',
        time: this.formatDateForApi(this.currentPickDate),
        type: this.filterOptions[this.activeFilter].name
      }
      // console.log('更新数据参数:', params)
      const res = await getVisitFunctionTopData(params)
      if (res.code == 200) {
        this.chartData = res.data.map(item => {
          return {
            name: item.module_name,
            count: item.count,
            percentage: item.percentage
          }
        })
        // 更新当前日期显示
        this.currentDate = this.formatTimeDisplay(this.formatDateForApi(this.currentPickDate))
      }
    },

    changeFilter(index) {
      if (this.filterOptions[index].disabled) return
      this.activeFilter = index
      // 使用当前选择的日期更新数据，而不是固定的最后一天日期
      this.updateDataByDate()
    },

    getLastDay() {
      if (this.dateRange && this.dateRange.length > 0) {
        const date = new Date(this.dateRange[1])
        const year = date.getFullYear()
        const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
        const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        return `${year}-${month}-${day}`
      }
      return ''
    },

    formatDateForApi(date) {
      // 格式化日期为API需要的格式
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
    },

    formatTimeDisplay(timeStr) {
      // 格式化时间显示
      if (!timeStr) return '暂无数据'
      const date = new Date(timeStr)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const weekDay = weekDays[date.getDay()]
      return `${weekDay} ${year}/${month}/${day}`
    },

    prevDate() {
      // 实现日期向前切换逻辑
      if (!this.canGoPrev) return
      const newDate = new Date(this.currentPickDate)
      newDate.setDate(newDate.getDate() - 1) // 左箭头是前一天
      newDate.setHours(0, 0, 0, 0) // 确保设置为当天的开始时间
      this.currentPickDate = newDate
      this.updateDataByDate()
      // console.log('向前切换日期')
    },
    nextDate() {
      // 实现日期向后切换逻辑
      if (!this.canGoNext) return
      const newDate = new Date(this.currentPickDate)
      newDate.setDate(newDate.getDate() + 1) // 右箭头是后一天
      newDate.setHours(0, 0, 0, 0) // 确保设置为当天的开始时间
      this.currentPickDate = newDate
      this.updateDataByDate()
      // console.log('向后切换日期')
    }
  }
}
</script>

<style lang="scss" scoped>
.page-top10-container {
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: 100%;
}

.header-section {
  margin-bottom: 20px;
}

.title-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.widget-title {
  font-size: 20px;
  font-weight: 600;
  color: #333333;
  margin: 0;
}

.date-selector {
  display: flex;
  align-items: center;
}

.date-nav {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #666666;
}

.date-arrow {
  cursor: pointer;
  font-size: 18px;
  color: #999999;
  transition: color 0.3s;
  
  &:hover {
    color: #409eff;
  }

  &.disabled {
    cursor: not-allowed;
    color: #cccccc;
    
    &:hover {
      color: #cccccc;
    }
  }
}

.date-text {
  font-size: 16px;
  color: #666666;
  min-width: 120px;
  text-align: center;
}

.filter-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
}

.filter-btn {
  padding: 8px 16px;
  font-size: 16px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background: #ffffff;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    color: #409eff;
    border-color: #c6e2ff;
    background-color: #ecf5ff;
  }
  
  &.active,
  &.el-button--primary {
    background-color: #409eff;
    border-color: #409eff;
    color: #ffffff;
  }
}

.chart-container {
  .chart-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding: 12px 8px;
    gap: 4px;
    position: relative;
    border-bottom: 1px solid #f0f0f0;
    background-color: #fafafa;
    border-radius: 4px;
    transition: background-color 0.2s;
    
    &:hover {
      background-color: #f5f5f5;
    }
    
    &:last-child {
      margin-bottom: 0;
      border-bottom: none;
    }
  }
  
  .item-label {
    font-size: 16px;
    color: #333333;
    font-weight: 500;
    width: 140px;
    min-width: 140px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex-shrink: 0;
    font-family: 'Courier New', monospace; // 页面路径使用等宽字体
  }
  
  .bar-value-left {
    font-size: 16px;
    color: #333333;
    font-weight: 600;
    width: 60px;
    text-align: right;
    flex-shrink: 0;
  }
  
  .bar-value-right {
    font-size: 14px;
    color: #999999;
    width: 50px;
    text-align: left;
    flex-shrink: 0;
  }
  
  .bar-container {
    width: 200px;
    height: 10px;
    background-color: #e8e8e8;
    border-radius: 5px;
    overflow: hidden;
    position: relative;
    flex-shrink: 0;
    border: 1px solid #d9d9d9;
  }
  
  .bar-fill {
    height: 100%;
    background: linear-gradient(90deg, #52c41a 0%, #73d13d 50%, #95de64 100%);
    border-radius: 4px;
    transition: width 0.6s ease-in-out;
    position: relative;
    box-shadow: 0 2px 6px rgba(82, 196, 26, 0.4);
    border: 1px solid #52c41a;
    
    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.6) 50%, transparent 100%);
      animation: shimmer 2s infinite;
    }
  }
}

// 暂无数据样式
.no-data-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: #999999;
}

.no-data-icon {
  font-size: 48px;
  color: #cccccc;
  margin-bottom: 16px;
}

.no-data-text {
  font-size: 18px;
  font-weight: 500;
  color: #666666;
  margin-bottom: 8px;
}

.no-data-desc {
  font-size: 14px;
  color: #999999;
}

@keyframes shimmer {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .title-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .filter-buttons {
    flex-wrap: wrap;
  }
  
  .item-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .item-values {
    align-self: flex-end;
  }
}
</style>
